/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (n) {
    if (n === 1) return [[1]]

    // 初始化二维数组
    let resArr = new Array(n).fill(0).map(() => new Array(n).fill(0)),
        left = 0,
        top = 0,
        right = n - 1,
        bottom = n - 1,
        count = 1

    // 和54思路相同
    while (left <= right && top <= bottom) {
        for (let column = left; column <= right; column++) {
            resArr[top][column] = count++
        }
        for (let row = top + 1; row <= bottom; row++) {
            resArr[row][right] = count++
        }
        if (left < right && top < bottom) {
            for (let column = right - 1; column >= left; column--) {
                resArr[bottom][column] = count++
            }
            for (let row = bottom - 1; row > top; row--) {
                resArr[row][left] = count++
            }
        }

        [left, top, right, bottom] = [left + 1, top + 1, right - 1, bottom - 1]
    }

    return resArr
};

console.log(generateMatrix(10))